import { Card, Row, Col, Button, Spinner } from "react-bootstrap";
import { format, set } from "date-fns";
import { useEffect, useState } from "react";
import ideaCanvasService from "../services/ideaCanvasService";

const IdeaCanvasList = ({ load }) => {
  const [ideas, setIdeas] = useState([]);
  const canvasAspectMap = {
    customer_segmentation: "1. 客户细分",
    value_propositions: "2. 价值主张",
    channels: "3. 渠道通路",
    customer_relationships: "4. 客户关系",
    income_streams: "5. 收入来源",
    key_resources: "6. 核心资源",
    key_activities: "7. 关键业务",
    key_partnerships: "8. 重要合作",
    cost_structure: "9. 成本结构",
  };

  const deleteIdea = (id) => {
    setDeleting(id);
    ideaCanvasService.deleteIdea(id)
      .then(() => {
        fetchIdeas();
      })
      .finally(() => {
        setDeleting(null);
      });
  };

  const [loading, setLoading] = useState(true);
  const [deleting, setDeleting] = useState(null);

  async function fetchIdeas() {
    ideaCanvasService
      .getIdeas()
      .then((data) => {
        console.log("ideaCanvasService.getIdeas()", data);
        setIdeas(data);
      })
      .finally(() => {
        setLoading(false);
      });
    }

  useEffect(() => {
    setLoading(true);
    fetchIdeas();
  }, [load]);

  if (loading) {
    return (
      <Col style={{ textAlign: "center" }}>
        <Spinner animation="grow" variant="info" />
      </Col>
    );
  }

  return (
    <Row xs={1} md={2} className="g-4">
      {ideas.length === 0 ? (
        <Col style={{ textAlign: "center" }}>
          <p>No ideas available</p>
        </Col>
      ) : (
        ideas.map((idea) => (
          <Col key={idea.id}>
            <Card>
              <Card.Body
                onClick={() => console.log(idea)}
                style={{ cursor: "pointer" }}
              >
                <Card.Title>{idea.title}</Card.Title>
                <Card.Text>
                  {Object.entries(canvasAspectMap).map(([key, value]) => (
                    <div key={key}>
                      <strong>{value}:</strong> {idea.data[key]}
                    </div>
                  ))}
                </Card.Text>
              </Card.Body>
              <Card.Footer>
                <Button
                  variant="light"
                  onClick={() => deleteIdea(idea.id)}
                  disabled={deleting === idea.id}
                >
                  {deleting === idea.id ? (
                    <Spinner animation="border" size="sm" />
                  ) : (
                    <i className="bi bi-trash"></i>
                  )}
                </Button>
                {format(new Date(idea.created_at), "MMMM d, yyyy h:mm:ss a")}
              </Card.Footer>
            </Card>
          </Col>
        ))
      )}
    </Row>
  );
};

export default IdeaCanvasList;
